#include "skmodelparameter.h"
#include <QDebug>
#include <QTableView>

SkModelParameter::SkModelParameter(SketchModelWrapper* modelo,QObject *parent) :
QAbstractTableModel(parent)
{
	model = modelo;
	map = new std::map<int,skreal>(model->getParameterData());
}
int SkModelParameter::rowCount( const QModelIndex & parent  ) const {
	Q_UNUSED(parent);
	return map->size();
}
int SkModelParameter::columnCount ( const QModelIndex & parent ) const{
	Q_UNUSED(parent);
	return 2;
}
QVariant SkModelParameter::data ( const QModelIndex & index, int role ) const{
	if (!index.isValid())
		return QVariant();
	if(role==Qt::DisplayRole || role==Qt::EditRole){

		if(index.column()==0){
			int i=0;
			for(std::map<int,skreal>::iterator it = map->begin(); it!=map->end(); it++){
				if(index.row()==i){
					return it->first;
				}
				i++;
			}

		}else if(index.column()==1){
			int i=0;
			for(std::map<int,skreal>::iterator it = map->begin(); it!=map->end(); it++){
				if(index.row()==i){
					QString s;
					return s.setNum(it->second,'f',2);
				}
				i++;
			}
		}

	}

	return QVariant();

}
bool SkModelParameter::setData ( const QModelIndex & index, const QVariant & value, int role  ) {

	if(role!=Qt::EditRole) return false;
	bool ok;
	double val = value.toDouble(&ok);
	qDebug() << "Val : " << val;
	if(ok){

		int id =0 ;

		int i=0;
		for(std::map<int,skreal>::iterator it = map->begin(); it!=map->end(); it++){
			if(index.row()==i){
				id = it->first;
			}
			i++;
		}
		model->setParameter(id,val);
		resetList();
		qDebug() << "ID :" << id << "Val :" << val ;
	}
	emit dataChanged (index,index) ;
	return true;
}

QVariant SkModelParameter::headerData(int section, Qt::Orientation orientation,int role ) const{

	if (role != Qt::DisplayRole) return QVariant();

	if (orientation == Qt::Horizontal){

		switch(section){
		case 0:
			return QString("id");
		case 1:
			return QString("value");
		}

	}

	return QString("%1").arg(section);
}

Qt::ItemFlags SkModelParameter::flags(const QModelIndex &index) const{

	if (!index.isValid())
		return Qt::ItemIsEnabled;

	switch(index.column()){
	case 0:
		return QAbstractItemModel::flags(index);
	case 1:
		return QAbstractItemModel::flags(index) | Qt::ItemIsEditable;

	}
	return NULL;
}

void SkModelParameter::resetList(){
	delete map;

	map = new std::map<int,skreal>(model->getParameterData());
	reset();
}

SkModelParameter::~SkModelParameter(){
	delete map;
}
